import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'

// Singleton markdown-it instance
const md = new MarkdownIt({
  html: false,
  linkify: true,
  typographer: true,
  highlight(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs"><code>${hljs.highlight(code, { language: lang, ignoreIllegals: true }).value}</code></pre>`
      } catch (e) { /* ignore */ }
    }
    const escaped = md.utils.escapeHtml(code)
    return `<pre class="hljs"><code>${escaped}</code></pre>`
  }
})

// Basic security: escape & filter script tags from rendered output (defense-in-depth)
export function renderMarkdown(text) {
  if (!text) return ''
  // markdown-it already escapes unsafe HTML if html:false
  const rendered = md.render(text)
  return rendered.replace(/<script.*?>[\s\S]*?<\/script>/gi, '')
}
